package com.takepoints.mobile;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.takepoints.android.bo.Card;
import com.takepoints.android.TPConst;
import com.takepoints.android.services.TPServices;
import com.takepoints.android.util.AnimationUtil;
import com.takepoints.android.util.DateUtil;
import com.takepoints.android.util.DownloadImageTask;
import com.takepoints.android.util.JsonParser;
import com.takepoints.android.util.StringUtil;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;

public class MyCards extends BaseActivity {
	
	private ListView cardListView = null;
	private CardListAdapter cardAdapter = null;
	private Button btnLoadMore = null;
	
	private int nextPage = 1;
	
	private final String IMG_PATH = "https://www.takepoints.com/public/uploads/tmobile/";
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
	        .detectDiskReads()
	        .detectDiskWrites()
	        .detectNetwork()   // or .detectAll() for all detectable problems
	        .penaltyLog()
	        .build());
			
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
	        .detectLeakedSqlLiteObjects()
	        .penaltyLog()
	        .penaltyDeath()
	        .build());
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myitems);
        
        TextView txtHeader = (TextView)findViewById(R.id.txtHeader);
        txtHeader.setText(R.string.title_mycard);
        manageMenu(3);
        
        ImageView imgAddItem = (ImageView)findViewById(R.id.imgAddItem);
        imgAddItem.setOnClickListener(new View.OnClickListener(){
			 public void onClick(View view) {
				 Intent cardsInt = new Intent(view.getContext(), TPCards.class);
				 startActivityForResult(cardsInt, 0);
			 }
        });
        
        //progressDlg = new ProgressDialog(this);
        //progressDlg.setTitle("Takepoints.com");
        //progressDlg.setMessage("Loading Cards ...");
        
        cardListView = (ListView)findViewById(R.id.lstItems);
        cardListView.setLayoutAnimation(new AnimationUtil().getSlideDownAnimateCtrl());
        
        btnLoadMore = (Button)findViewById(R.id.btnLoadMore);
        btnLoadMore.setOnClickListener(new View.OnClickListener(){
			 public void onClick(View view) {
				 new FetchMyCards(view.getContext()).execute(String.valueOf(nextPage));
			 }
        });
        
        cardAdapter = new CardListAdapter(new ArrayList<Card>());
        cardListView.setAdapter(cardAdapter);
        
        new FetchMyCards(this).execute("1");
	}
	
	@Override
	public void onBackPressed(){
		Intent homeInt = new Intent(this, Takepoints.class);
		startActivityForResult(homeInt, 0);
		return;
	}
	
	private class CardListAdapter extends BaseAdapter {
		private List<Card> cards;
		private LayoutInflater mInflater;

		public CardListAdapter(List<Card> cards){
			mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.cards = cards;
		}
		
		public void add(Card card){
			cards.add(card);
			notifyDataSetChanged();
		}
		
		public void removeAll(){
			cards.clear();
			notifyDataSetChanged();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			final View rowView = (convertView!=null)?convertView:mInflater.inflate(R.layout.mycardrow, null);
			final Card card = cards.get(position);
			if(card != null){
				int total = Integer.parseInt(card.getStar());
				int approved = Integer.parseInt(card.getApprove());
				int pending = Integer.parseInt(card.getPending());
				
				ImageView imgCard = (ImageView)rowView.findViewById(R.id.imgCard);
				if(imgCard != null){
					Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + card.getImageName());
					if(bitmap != null){
						if(total > 0 && approved >= total){	// Card Full
							Drawable d = new BitmapDrawable(bitmap);
							imgCard.setBackgroundDrawable(d);
							
							imgCard.setImageResource(R.drawable.card_full);
						} else{
							imgCard.setImageBitmap(bitmap);
						}
					} else{
						if(total > 0 && approved >= total){	// Card Full
							imgCard.setImageResource(R.drawable.card_full);
						}
						imgCard.setTag(IMG_PATH + card.getImageName());
						new DownloadImageTask().execute(imgCard);
					}
				}
				TextView txtPoints = (TextView)rowView.findViewById(R.id.txtPoints);
				txtPoints.setText(card.getOfferPts());
				
				LinearLayout lnrDetail = (LinearLayout)rowView.findViewById(R.id.lnrDetail);
				lnrDetail.removeAllViews();
				if(lnrDetail != null){
					String cardNo = "";
					if(!StringUtil.isEmpty(card.getCardNo())){
						cardNo = " #" + card.getCardNo();
					}
					TextView txtTitle = new TextView(lnrDetail.getContext());
					txtTitle.setText(card.getCustomerName() + " (" + card.getSiteName() + ") " + cardNo);
					txtTitle.setTextSize(12);
					txtTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
					txtTitle.setTextColor(Color.parseColor("#006600"));
					txtTitle.setHeight(LayoutParams.WRAP_CONTENT);
					txtTitle.setPadding(10, 1, 1, 1);
					txtTitle.setSingleLine(false);
					lnrDetail.addView(txtTitle);
					
					TextView txtDesc = new TextView(lnrDetail.getContext());
					txtDesc.setText(card.getItemName());
					txtDesc.setTextSize(11);
					txtDesc.setTextColor(Color.parseColor("#404a4a"));
					txtDesc.setHeight(LayoutParams.WRAP_CONTENT);
					txtDesc.setPadding(9, 1, 1, 1);
					txtDesc.setSingleLine(false);
					lnrDetail.addView(txtDesc);
					
					String dayLeft = null;
					try{
						dayLeft = "เหลืออีก  " + DateUtil.getRemainDate(DateUtil.strToDate(card.getEndDate(), "dd-MMM-yy"));
					} catch(Exception e){
						dayLeft = "ภายในวันที่ " + card.getEndDate();
					}
					TextView txtPointGet = new TextView(lnrDetail.getContext());
					txtPointGet.setText( dayLeft );
					txtPointGet.setTextSize(9);
					txtPointGet.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
					txtPointGet.setTextColor(Color.parseColor("#FF6600"));
					txtPointGet.setPadding(10, 3, 1, 1);
					lnrDetail.addView(txtPointGet);
				}
				
				rowView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 Intent myCardDetailInt = new Intent(view.getContext(), MyCardDetail.class);
						 myCardDetailInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
						 myCardDetailInt.putExtra("cardId", card.getItemId());
						 myCardDetailInt.putExtra("siteName", card.getCustomerName() + " (" + card.getSiteName() + ") " + " #" + card.getCardNo());
						 //myCardDetailInt.putExtra("totalOrng", card.getStar());
						 startActivity(myCardDetailInt);
					 }
				});
				rowView.setOnTouchListener(new View.OnTouchListener(){
					 public boolean onTouch(View v, MotionEvent event){
						 int action = event.getAction();
						 switch(action){
						 	case MotionEvent.ACTION_DOWN:
						 		rowView.setBackgroundColor(Color.LTGRAY);
						 		break;
						 	case MotionEvent.ACTION_UP:
						 		rowView.setBackgroundResource(R.drawable.bg_my_card);
						 		break;
						 	case MotionEvent.ACTION_MOVE:
						 		rowView.setBackgroundResource(R.drawable.bg_my_card);
						 		break;
						 	case MotionEvent.ACTION_CANCEL:
						 		//rowView.setBackgroundColor(Color.parseColor("#9aa1a0"));
						 		rowView.setBackgroundResource(R.drawable.bg_my_card);
						 		break;
						 	default:
						 		break;
						 }
						 return false;
					}
				 });
			}
			return rowView;
		}

		@Override
		public int getCount() {
			return cards.size();
		}

		@Override
		public Object getItem(int position) {
			return cards.get(position);
		}

		@Override
		public long getItemId(int position) {
			return cards.get(position).hashCode();
		}
	}
	
	class FetchMyCards extends AsyncTask<String, Void, List<Card>>{
    	
		private Context context = null;
		//private ImageView imgRefresh = null;
		private ProgressDialog progressDlg = null;
		
		FetchMyCards(Context context){
			this.context = context;
		}
		
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            //imgRefresh = (ImageView)findViewById(R.id.imgRefresh);
            //imgRefresh.startAnimation(new AnimationUtil().getRotateAnimation(25f, 25f));
            progressDlg = ProgressDialog.show(context, "Takepoints.com", "กำลังโหลด บัตรสะสม ...", true);
        }
        
        @Override
        protected List<Card> doInBackground(String... params){
        	int page = Integer.parseInt(params[0]);
        	List<Card> cards = TPServices.getCardList( getSharedIntValue(TPConst.PRF_MEMBER_ID)
													  , TPServices.PROMOTION_TYPE_CARD
													  , page);
Log.v("MyCards", "page = " + page + " , " + (cards!=null?cards.size():0));
        	return cards;
        }
        
        @Override
        protected void onPostExecute(List<Card> result){
        	int rows = (result==null)?0:result.size();
    		try{
    			for(int i=0; i<rows; i++){
    				cardAdapter.add(result.get(i));
    			}
	            
	            if(rows > 0){
	    			Card card = result.get(0);
		            ++nextPage;
		            if(nextPage > card.getTotalPage()){
		            	btnLoadMore.setVisibility(View.GONE);
		            }
	        	} else{
	        		btnLoadMore.setVisibility(View.GONE);
	        	}
    		} catch(Exception e){
    			alert("ผิดพลาด : " + e.getMessage());
    		}
        	progressDlg.dismiss();
        }
        
    }
	
	
	
	
	private JsonParser jsonParser = new JsonParser();
	
	/** 
     * Background Async Task to Get complete product details 
     * */
    class GetProductDetails extends AsyncTask<String, String, String>{
    	
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            
        }
        
        protected String doInBackground(String... params){
            // updating UI from Background Thread
            runOnUiThread(new Runnable(){
                public void run(){
                	// Check for success tag
                    int success;
                    try{
                    	List<NameValuePair> params = new ArrayList<NameValuePair>(); 
                        params.add(new BasicNameValuePair("pid", ""));
                        
                    	JSONObject json = jsonParser.makeHttpRequest("", "GET", params);
                    	
                    } catch(Exception e){
                        e.printStackTrace();
                    }
                }
            });
            return null;
        }
        
        protected void onPostExecute(String file_url){ 
            // dismiss the dialog once got all details
        }
        
    }
    
}
